package com.aode.downloadmusic.view.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aode.common.bean.request.Request;
import com.aode.common.bean.response.Music;
import com.aode.downloadmusic.R;
import com.aode.downloadmusic.adapter.DownloadMusicAdapter;
import com.aode.downloadmusic.databinding.ActivityDownloadBinding;
import com.aode.downloadmusic.listener.DownloadListener;
import com.aode.downloadmusic.network.DownloadUtil;
import com.aode.downloadmusic.ui.KbWithWordsCircleProgressBar;
import com.aode.downloadmusic.viewmodel.DownloadViewModel;
import com.aode.musicplay.MusicPlayActivity;
import com.aode.utils.download.SystemUtil;
import com.aode.utils.download.permission.KbPermission;
import com.aode.utils.download.permission.KbPermissionListener;
import com.aode.utils.download.permission.KbPermissionUtils;
import com.aode.utils.main.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class DownloadActivity extends AppCompatActivity implements DownloadMusicAdapter.MusicInterface  {
    private ActivityDownloadBinding downloadBinding;
    private Context mContext;
    private static final String TAG = "DownloadPictureActivity";
    private KbWithWordsCircleProgressBar mCircleProgress;
    private FrameLayout mCircleProgressLayout;
    private DownloadViewModel downloadViewModel;
    private DownloadMusicAdapter downloadMusicAdapter;
    private List<Music> musics = new ArrayList<>();
    private Music music;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        downloadBinding = DataBindingUtil.setContentView(this, R.layout.activity_download);
        mCircleProgress = downloadBinding.circleProgress;
        mCircleProgressLayout = downloadBinding.flCircleProgress;
        mContext = this;
        downloadViewModel = ViewModelProviders.of(this).get(DownloadViewModel.class);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            SystemUtil.setLightStatusBar(this, Color.WHITE);
        }
         music = (Music) getIntent().getParcelableExtra("music");
        if(music!=null){
            initPermission();
        }

        initData();

    }

    private void initListener() {
        downloadViewModel.getMusicLiveData().observe(this, music -> {
            musics = music;
            Log.e(TAG,music.size()+"");
            if(musics!=null&&!musics.isEmpty()&&musics.size()>0){
                initRecyclerView((ArrayList<Music>) musics);
            }
        });
    }

    private void initRecyclerView(ArrayList<Music> musics) {
        downloadMusicAdapter = new DownloadMusicAdapter(this,musics,this);
        downloadBinding.downloadRecycler.setLayoutManager(new LinearLayoutManager(this ,LinearLayoutManager.VERTICAL,false));
        downloadBinding.downloadRecycler.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        downloadBinding.downloadRecycler.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));
        downloadBinding.downloadRecycler.setAdapter(downloadMusicAdapter);

    }


    private void initData() {
        downloadViewModel.getMusic();
        initListener();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initListener();
    }

    private void initPermission() {
        if (KbPermissionUtils.needRequestPermission()) {
            KbPermission.with(this)
                    .requestCode(100)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callBack(new KbPermissionListener() {
                        @Override
                        public void onPermit(int requestCode, String... permission) {
                            downloadMusic();
                        }

                        @Override
                        public void onCancel(int requestCode, String... permission) {
                            KbPermissionUtils.goSetting(mContext);
                        }
                    })
                    .send();
        } else {
            downloadMusic();
        }
    }
    private void downloadMusic() {
        //下载相关
        DownloadUtil downloadUtil = new DownloadUtil();


        downloadUtil.downloadFile(music, new DownloadListener() {
            @Override
            public void onStart() {
//                Log.e(TAG, "onStart: ");
                runOnUiThread(() -> mCircleProgressLayout.setVisibility(View.VISIBLE));
            }

            @Override
            public void onProgress(final int currentLength) {
//                Log.e(TAG, "onLoading: " + currentLength);
                runOnUiThread(() -> mCircleProgress.setProgress(currentLength));
            }

            @Override
            public void onFinish(final String localPath) {
                Log.e(TAG, "onFinish: " + localPath);
                runOnUiThread(() -> {
                    mCircleProgressLayout.setVisibility(View.GONE);
                    ToastUtils.show(mContext,"下载成功");
//                    Glide.with(mContext).load(localPath).into(mPicture);
                });
            }

            @Override
            public void onFailure(final String erroInfo) {
//                Log.e(TAG, "onFailure: " + erroInfo);
                runOnUiThread(() -> {
                    mCircleProgressLayout.setVisibility(View.GONE);
                    Toast.makeText(mContext, erroInfo, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    //必须添加，否则第一次请求成功权限不会走回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        KbPermission.onRequestPermissionResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onItemClick(Music music) {

        Intent intent = new Intent();
        intent.setClass(DownloadActivity.this, MusicPlayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("music",music);
        intent.putExtras(bundle);
        startActivityForResult(intent, Request.HOME_TO_PLAYLIST);
    }
}
